/**
 * 字典数据相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 获取字典数据列表
 * @param {object} params - 查询参数
 * @returns {Promise} 字典数据列表
 */
export const getDictList = (params = {}) => {
  return request.get('/dict/list', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '', category } = queryParams
    
    const mockDicts = Array.from({ length: 50 }, (_, index) => ({
      id: index + 1,
      code: `DICT_${String(index + 1).padStart(3, '0')}`,
      name: `字典${index + 1}`,
      category: ['system', 'business', 'user', 'card', 'mediation'][Math.floor(Math.random() * 5)],
      categoryName: ['系统字典', '业务字典', '用户字典', '卡片字典', '调解字典'][Math.floor(Math.random() * 5)],
      description: `这是字典${index + 1}的描述信息`,
      status: Math.random() > 0.1 ? 1 : 0,
      statusName: Math.random() > 0.1 ? '启用' : '禁用',
      sort: index + 1,
      itemCount: Math.floor(Math.random() * 20) + 5,
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString()
    }))
    
    // 过滤数据
    let filteredDicts = mockDicts
    if (keyword) {
      filteredDicts = mockDicts.filter(dict => 
        dict.code.includes(keyword) || 
        dict.name.includes(keyword) ||
        dict.description.includes(keyword)
      )
    }
    if (category) {
      filteredDicts = filteredDicts.filter(dict => dict.category === category)
    }
    
    // 分页
    const total = filteredDicts.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredDicts.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取字典详情
 * @param {number} id - 字典ID
 * @returns {Promise} 字典详情
 */
export const getDictDetail = (id) => {
  return request.get(`/dict/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      code: `DICT_${String(id).padStart(3, '0')}`,
      name: `字典${id}`,
      category: 'system',
      categoryName: '系统字典',
      description: `这是字典${id}的详细描述信息`,
      status: 1,
      statusName: '启用',
      sort: Number(id),
      itemCount: Math.floor(Math.random() * 20) + 5,
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString(),
      items: Array.from({ length: Math.floor(Math.random() * 10) + 5 }, (_, index) => ({
        id: index + 1,
        dictId: Number(id),
        code: `ITEM_${String(index + 1).padStart(3, '0')}`,
        label: `选项${index + 1}`,
        value: String(index + 1),
        description: `这是选项${index + 1}的描述`,
        status: Math.random() > 0.1 ? 1 : 0,
        statusName: Math.random() > 0.1 ? '启用' : '禁用',
        sort: index + 1,
        color: ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'][Math.floor(Math.random() * 5)],
        icon: ['user', 'setting', 'star', 'heart', 'like'][Math.floor(Math.random() * 5)],
        createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
        updateTime: new Date().toISOString()
      }))
    })
  })
}

/**
 * 创建字典
 * @param {object} data - 字典数据
 * @returns {Promise} 创建结果
 */
export const createDict = (data) => {
  return request.post('/dict', data, {}, (params) => {
    const { code, name, category } = params
    
    if (!code || !name || !category) {
      return mockError('请填写字典编码、名称和分类', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      ...params,
      itemCount: 0,
      status: 1,
      statusName: '启用',
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }, '字典创建成功')
  })
}

/**
 * 更新字典
 * @param {number} id - 字典ID
 * @param {object} data - 更新数据
 * @returns {Promise} 更新结果
 */
export const updateDict = (id, data) => {
  return request.put(`/dict/${id}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(id),
      ...params,
      updateTime: new Date().toISOString()
    }, '字典更新成功')
  })
}

/**
 * 删除字典
 * @param {number} id - 字典ID
 * @returns {Promise} 删除结果
 */
export const deleteDict = (id) => {
  return request.delete(`/dict/${id}`, {}, () => {
    return mockSuccess(null, '字典删除成功')
  })
}

/**
 * 获取字典项列表
 * @param {number} dictId - 字典ID
 * @param {object} params - 查询参数
 * @returns {Promise} 字典项列表
 */
export const getDictItems = (dictId, params = {}) => {
  return request.get(`/dict/${dictId}/items`, params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '' } = queryParams
    
    const mockItems = Array.from({ length: 30 }, (_, index) => ({
      id: index + 1,
      dictId: Number(dictId),
      code: `ITEM_${String(index + 1).padStart(3, '0')}`,
      label: `选项${index + 1}`,
      value: String(index + 1),
      description: `这是选项${index + 1}的描述信息`,
      status: Math.random() > 0.1 ? 1 : 0,
      statusName: Math.random() > 0.1 ? '启用' : '禁用',
      sort: index + 1,
      color: ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'][Math.floor(Math.random() * 5)],
      icon: ['user', 'setting', 'star', 'heart', 'like'][Math.floor(Math.random() * 5)],
      parentId: index > 10 ? Math.floor(Math.random() * 10) + 1 : null,
      parentLabel: index > 10 ? `选项${Math.floor(Math.random() * 10) + 1}` : null,
      level: index > 10 ? 2 : 1,
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString()
    }))
    
    // 过滤数据
    let filteredItems = mockItems
    if (keyword) {
      filteredItems = mockItems.filter(item => 
        item.code.includes(keyword) || 
        item.label.includes(keyword) ||
        item.value.includes(keyword)
      )
    }
    
    // 排序
    filteredItems.sort((a, b) => a.sort - b.sort)
    
    // 分页
    const total = filteredItems.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredItems.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 创建字典项
 * @param {number} dictId - 字典ID
 * @param {object} data - 字典项数据
 * @returns {Promise} 创建结果
 */
export const createDictItem = (dictId, data) => {
  return request.post(`/dict/${dictId}/items`, data, {}, (params) => {
    const { code, label, value } = params
    
    if (!code || !label || !value) {
      return mockError('请填写字典项编码、标签和值', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      dictId: Number(dictId),
      ...params,
      status: 1,
      statusName: '启用',
      level: 1,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }, '字典项创建成功')
  })
}

/**
 * 更新字典项
 * @param {number} dictId - 字典ID
 * @param {number} itemId - 字典项ID
 * @param {object} data - 更新数据
 * @returns {Promise} 更新结果
 */
export const updateDictItem = (dictId, itemId, data) => {
  return request.put(`/dict/${dictId}/items/${itemId}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(itemId),
      dictId: Number(dictId),
      ...params,
      updateTime: new Date().toISOString()
    }, '字典项更新成功')
  })
}

/**
 * 删除字典项
 * @param {number} dictId - 字典ID
 * @param {number} itemId - 字典项ID
 * @returns {Promise} 删除结果
 */
export const deleteDictItem = (dictId, itemId) => {
  return request.delete(`/dict/${dictId}/items/${itemId}`, {}, () => {
    return mockSuccess(null, '字典项删除成功')
  })
}

/**
 * 根据字典编码获取字典项
 * @param {string} dictCode - 字典编码
 * @returns {Promise} 字典项列表
 */
export const getDictItemsByCode = (dictCode) => {
  return request.get(`/dict/code/${dictCode}/items`, {}, {}, () => {
    // 根据不同的字典编码返回不同的数据
    const dictData = getDictDataByCode(dictCode)
    return mockSuccess(dictData)
  })
}

/**
 * 批量获取字典数据
 * @param {Array} dictCodes - 字典编码数组
 * @returns {Promise} 字典数据
 */
export const getBatchDictData = (dictCodes) => {
  return request.post('/dict/batch', { dictCodes }, {}, (params) => {
    const { dictCodes } = params
    const result = {}
    
    dictCodes.forEach(code => {
      result[code] = getDictDataByCode(code)
    })
    
    return mockSuccess(result)
  })
}

/**
 * 获取字典分类列表
 * @returns {Promise} 分类列表
 */
export const getDictCategories = () => {
  return request.get('/dict/categories', {}, {}, () => {
    return mockSuccess([
      { code: 'system', name: '系统字典', description: '系统相关的字典数据' },
      { code: 'business', name: '业务字典', description: '业务相关的字典数据' },
      { code: 'user', name: '用户字典', description: '用户相关的字典数据' },
      { code: 'card', name: '卡片字典', description: '卡片相关的字典数据' },
      { code: 'mediation', name: '调解字典', description: '调解相关的字典数据' },
      { code: 'notice', name: '通知字典', description: '通知相关的字典数据' },
      { code: 'store', name: '商店字典', description: '商店相关的字典数据' }
    ])
  })
}

/**
 * 导出字典数据
 * @param {object} params - 导出参数
 * @returns {Promise} 导出结果
 */
export const exportDictData = (params = {}) => {
  return request.get('/dict/export', params, { responseType: 'blob' }, () => {
    return mockSuccess({
      filename: `dict_data_${new Date().toISOString().split('T')[0]}.xlsx`,
      url: '/downloads/dict_data.xlsx'
    }, '字典数据导出成功')
  })
}

/**
 * 导入字典数据
 * @param {FormData} formData - 文件数据
 * @returns {Promise} 导入结果
 */
export const importDictData = (formData) => {
  return request.upload('/dict/import', formData, {}, () => {
    return mockSuccess({
      totalCount: 100,
      successCount: 95,
      failCount: 5,
      failList: [
        { row: 3, reason: '字典编码重复' },
        { row: 7, reason: '字典名称为空' },
        { row: 12, reason: '分类不存在' },
        { row: 18, reason: '排序值无效' },
        { row: 25, reason: '状态值错误' }
      ]
    }, '字典数据导入完成')
  })
}

/**
 * 根据字典编码获取模拟数据
 * @param {string} dictCode - 字典编码
 * @returns {Array} 字典项数组
 */
function getDictDataByCode(dictCode) {
  const dictDataMap = {
    // 卡片类型
    'CARD_TYPE': [
      { code: '1', label: '储值卡', value: '1', color: '#1890ff' },
      { code: '2', label: '会员卡', value: '2', color: '#52c41a' },
      { code: '3', label: '积分卡', value: '3', color: '#faad14' },
      { code: '4', label: '折扣卡', value: '4', color: '#f5222d' }
    ],
    // 卡片状态
    'CARD_STATUS': [
      { code: '1', label: '正常', value: '1', color: '#52c41a' },
      { code: '2', label: '冻结', value: '2', color: '#faad14' },
      { code: '3', label: '挂失', value: '3', color: '#f5222d' },
      { code: '4', label: '注销', value: '4', color: '#d9d9d9' }
    ],
    // 调解状态
    'MEDIATION_STATUS': [
      { code: '1', label: '待受理', value: '1', color: '#faad14' },
      { code: '2', label: '调解中', value: '2', color: '#1890ff' },
      { code: '3', label: '调解成功', value: '3', color: '#52c41a' },
      { code: '4', label: '调解失败', value: '4', color: '#f5222d' },
      { code: '5', label: '已撤销', value: '5', color: '#d9d9d9' }
    ],
    // 通知类型
    'NOTICE_TYPE': [
      { code: '1', label: '政务通知', value: '1', color: '#1890ff' },
      { code: '2', label: '教育培训', value: '2', color: '#52c41a' },
      { code: '3', label: '意见征集', value: '3', color: '#faad14' },
      { code: '4', label: '公示公告', value: '4', color: '#722ed1' }
    ],
    // 性别
    'GENDER': [
      { code: '1', label: '男', value: '1', color: '#1890ff' },
      { code: '2', label: '女', value: '2', color: '#f5222d' }
    ],
    // 审核状态
    'AUDIT_STATUS': [
      { code: '1', label: '待审核', value: '1', color: '#faad14' },
      { code: '2', label: '审核通过', value: '2', color: '#52c41a' },
      { code: '3', label: '审核拒绝', value: '3', color: '#f5222d' }
    ],
    // 启用状态
    'ENABLE_STATUS': [
      { code: '1', label: '启用', value: '1', color: '#52c41a' },
      { code: '0', label: '禁用', value: '0', color: '#d9d9d9' }
    ],
    // 优先级
    'PRIORITY': [
      { code: '1', label: '普通', value: '1', color: '#d9d9d9' },
      { code: '2', label: '重要', value: '2', color: '#faad14' },
      { code: '3', label: '紧急', value: '3', color: '#f5222d' }
    ]
  }
  
  return dictDataMap[dictCode] || []
}